import zh from "./langs/zh";
import en from "./langs/en";
import locale from "element-ui/lib/locale";
import enLocale from "element-ui/lib/locale/lang/en";
import zhLocale from "element-ui/lib/locale/lang/zh-CN";

/**
 * 批量转换中英文
 * @param {} list list格式['保存*save']
 * @returns
 */
function toCase(list) {
  let ch = {};
  let en = {};
  list.forEach((str) => {
    let strs = str.split("*");
    if (strs.length == 2 && strs[1]) {
      let key = strs[1]
        .replace(/\s+[a-z]{1}/g, function (val) {
          return val.trim().toUpperCase();
        })
        .replace(/-[a-z]{1}/g, function (val) {
          return val.substr(1).toUpperCase();
        })
        .replace(/\/[A-Z]{1}/g, function (val) {
          return val.substr(1).toUpperCase();
        })
        .replace(/^[A-Z]{1}/g, function (val) {
          return val.toLocaleLowerCase();
        })
        .replace(/\s+|-|&/g, "");
      if(!ch[key]){
        ch[key] = strs[0];
        en[key] = strs[1];
      }
    } else {
      console.log(strs[0]);
    }
  });
  return {
    ch,
    en,
  };
}

const lang = navigator.language === "en" ? "en" : "zh";

const messagesObj = {
  en: Object.assign(en, enLocale),
  zh: Object.assign(zh, zhLocale),
};

const translate = function (keys, messages, value) {
  if (!keys.length) {
    if (typeof messages === "string") {
      return messages.replace(/\{(.+?)\}/g, function (val) {
        return value[val.substr(1, val.length - 2)];
      });
    }
    return messages;
  }
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    let findKey = Object.keys(messages).find((j) => key === j);
    if (findKey) {
      return translate(keys.slice(i + 1), messages[findKey], value);
    }
  }
};

const i18n = {
  isEn(){
    return lang === 'en'; // 判断语言是否为英文
  },
  t(key, value) {
    if (!typeof key === "string" || !key) {
      return;
    }
    const keys = key.split(".");
    const messages = messagesObj[lang];
    return translate(keys, messages, value);
  },
  locales(i18nStr) {
    try {
      let i18nObj = typeof i18nStr === "string" ? JSON.parse(i18nStr) : i18nStr;
      return i18nObj[lang] !== undefined ? i18nObj[lang] : i18nStr;
    } catch (e) {
      // console.log(e)
    }
    return i18nStr;
  },
};

locale.i18n((key, value) => i18n.t(key, value));

export default i18n;
